#include <jni.h>
#include "jendocreat.h"
#include "dnamap.h"
#include <iostream>
using namespace std;
using namespace dnamap;

JNIEXPORT jstring JNICALL Java_endo_clink_translate
  (JNIEnv *env, jobject obj, jstring jdnaseq, jstring jcodonfname)
{
    const char* nativeDNAseq = env -> GetStringUTFChars(env, jdnaseq, JNI_FALSE);
    const char* nativecodonfname = env -> GetStringUTFChars(env, jcodonfname, JNI_FALSE);
    string res = translate(nativeDNAseq, nativecodonfname);
    jstring tstr = env -> NewStringUTF(env, res.c_str());
    return tstr;
}

JNIEXPORT jintArray JNICALL Java_endo_clink_sites
  (JNIEnv *env, jobject obj, jstring jdnaseq, jstring jcodonfname, jstring jsiteseq)
{
    const char* nativeDNAseq = env -> GetstringUTFChars(env, jdnaseq, JNI_FALSE);
    const char* nativecodonfname = env -> GetstringUTFChars(env, jcodonfname, JNI_FALSE);
    const char* nativeSiteseq = env -> GetstringUTFChars(env, jsiteseq, JNI_FALSE);
    sitelist mysite = synmut(nativeDNAseq, nativecodonfname, nativeSiteseq);
    int size = mysize.length();
    jintArray result;
    jint *fill;
    result = env -> NewIntArray(env, size);
    if(result == NULL)
    {
        return NULL;
    }
    fill = new jint[size];
    for(int i = 0; i < size; i++)
    {
        fill[i] = mysite[i];
    }
    env -> SetIntArrayRegion(env, result, 0, size, fill);
    delete fill;
    fill = NULL;
    return result;
}

string translate(const char* dnastr, const char* cfname)
{
    static char fname[1024];
    static protrans mytrans;
    if(strcmp(fname, cfname) != 0)
    {
        strcpy(fname, cfname);
        mytrans.readcodon(cfname);
    }
    dnaseq myseq;
    myseq.enter(dnastr);
    return mytrans.translate(myseq.getframe(0));
}

sitelist synmut(const char* dnastr, const char* cfname, const char* sitestr)
{
    static char fname[1024];
    static protrans mytrans;
    static string mydnaseq;
    static dnaseq myseq;
    if(strcmp(fname, cfname) != 0)
    {
        strcpy(fname, cfname);
        mytrans.readcodon(cfname);
    }
    if(mydnaseq.compare(dnastr) != 0)
    {
        mydnaseq = dnastr;
        myseq.enter(dnastr);
    }
    restriction rsite(sitestr, "A");
    string a = myseq.getframe(0);
    sitelist mysites = mytrans.synmut(a, rsite.siteseq);
    return mysites;
}

